﻿using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Threading;
using DataStore;
using DataStore.Domain;
using DataStore.Repositories;
using Infrastructure.CurrentData;
using Microsoft.Practices.Composite.Events;

namespace Infrastructure.ViewModels
{
    /// <summary>
    /// AllLanguages viewmodel
    /// </summary>
    public class AllLanguagesViewModel : DataModel
    {
        ObservableCollection<LanguageViewModel> _languages = new ObservableCollection<LanguageViewModel>();

        public AllLanguagesViewModel() : base()
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AllLanguagesViewModel"/> class.
        /// </summary>
        /// <param name="eventAggregator">The event aggregator.</param>
        public AllLanguagesViewModel(IEventAggregator eventAggregator) : base(eventAggregator)
        {
            Initialize();
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        void Initialize()
        {
            State = ModelState.Fetching;

            RefreshCategories();
        }

        /// <summary>
        /// Refreshes the categories.
        /// </summary>
        void RefreshCategories()
        {
            if (!ThreadPool.QueueUserWorkItem(FetchLanguagesCallback))
            {
                State = ModelState.Invalid;
            }
        }

        /// <summary>
        /// Gets or sets the languages.
        /// </summary>
        /// <value>The languages.</value>
        public ObservableCollection<LanguageViewModel> Languages
        {
            get
            {
                VerifyCalledOnUIThread();
                return _languages;
            }
            set
            {
                VerifyCalledOnUIThread();
                if (_languages != value)
                {
                    _languages = value;
                    OnPropertyChanged("Countries");
                }
            }
        }

        /// <summary>
        /// Fetches the languages callback.
        /// </summary>
        /// <param name="state">The state.</param>
        void FetchLanguagesCallback(object state)
        {
            IDatabase database = Current.Container.Resolve<IDatabase>();
            UnitOfWork unitOfWork = database.CreateUnitOfWork();
            IRepository<Language> repository = new LanguageRepository(unitOfWork);
            try
            {
                var languages = repository.All;

                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            Languages.Clear();
                                            foreach (var language in languages)
                                            {
                                                Languages.Add(new LanguageViewModel(EventAggregator ,language));
                                            }

                                            unitOfWork.Dispose();

                                            State = ModelState.Active;
                                            OnLoaded(this, EventArgs.Empty);
                                        }),
                    DispatcherPriority.ApplicationIdle);
            }
            catch (Exception e)
            {
                Log.Error("Failed to load Languages", e);

                unitOfWork.Dispose();
                Dispatcher.BeginInvoke(
                    new ThreadStart(delegate
                                        {
                                            State = ModelState.Invalid;
                                            OnLoaded(this, EventArgs.Empty);
                                        }),
                    DispatcherPriority.ApplicationIdle);

            }
        }


    }
}